﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NFinal.OAuth.Controllers
{
    public class QQController : BaseController
    {
        [GetHtml("/OAuth/QQ/Index.html")]
        public ActionResult Index()
        {
            //获得配置信息
            OAuthConfig config = ConfigHelper.get_config(this.config,"qq");
            if (config == null)
            {
                this.Write("出错了，您尚未配置QQ互联的API信息！");
                return null;
            }
            string state = Guid.NewGuid().ToString().Replace("-", "");
            Session["oauth_state"] = state;
            string send_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" + config.oauth_app_id + "&state=" + state + "&redirect_uri=" 
                + Uri.EscapeUriString(NFinal.Config.Configration.globalConfig.server.url + this.Url("ReturnUrl")) + "&scope=get_user_info,get_info";
            //开始发送
            return new RedirectResult(send_url);
        }
        [GetHtml("/OAuth/QQ/ReturnUrl.html")]
        public ActionResult ReturnUrl()
        {
            //取得返回参数
            string state = this.parameters["state"];
            string code = this.parameters["code"];

            string access_token = string.Empty;
            string expires_in = string.Empty;
            string client_id = string.Empty;
            string openid = string.Empty;

            if (Session["oauth_state"] == null || Session["oauth_state"].ToString() == "" || state != Session["oauth_state"].ToString())
            {
                this.Write("出错啦，state未初始化！");
                return null;
            }
            //获得配置信息
            OAuthConfig config = ConfigHelper.get_config(this.config, "qq");
            //第一步：获取Access Token
            Dictionary<string, object> dic1 = QQHelper.get_access_token(config,this.Url("ReturnUrl"),code, state);
            if (dic1 == null || !dic1.ContainsKey("access_token"))
            {
                this.Write("错误代码：，无法获取Access Token，请检查App Key是否正确！");
                return null;
            }
            access_token = dic1["access_token"].ToString();
            expires_in = dic1["expires_in"].ToString();

            //第二步：通过Access Token来获取用户的OpenID
            Dictionary<string, object> dic2 = QQHelper.get_open_id(access_token);
            if (dic2 == null || !dic2.ContainsKey("openid"))
            {
                if (dic2.ContainsKey("error"))
                {
                    this.Write("error：" + dic2["error"] + ",error_description：" + dic2["error_description"]);
                }
                else
                {
                    this.Write("出错啦，无法获取用户授权Openid！");
                }
                return null;
            }
            client_id = dic2["client_id"].ToString();
            openid = dic2["openid"].ToString();
            //储存获取数据用到的信息
            Session["oauth_name"] = "qq";
            Session["oauth_access_token"] = access_token;
            Session["oauth_openid"] = openid;

            //第三步：跳转到指定页面
            return new RedirectResult(this.config.JsonObject["oauth"]["loginSuccessUrl"]);
            //Response.Write("\access_token:" + access_token + ",openid:" + openid);
        }
        [GetHtml("/OAuth/QQ/Info.html")]
        public ActionResult Info()
        {
            string oauth_access_token = string.Empty;
            string oauth_openid = string.Empty;
            string oauth_name = string.Empty;

            if (Session["oauth_name"] == null || Session["oauth_access_token"] == null || Session["oauth_openid"] == null)
            {
                this.Write("{\"ret\":\"1\", \"msg\":\"出错啦，Access Token已过期或不存在！\"}");
                return null;
            }
            oauth_name = Session["oauth_name"].ToString();
            oauth_access_token = Session["oauth_access_token"].ToString();
            oauth_openid = Session["oauth_openid"].ToString();
            //获得配置信息
            OAuthConfig config = ConfigHelper.get_config(this.config, "qq");
            Dictionary<string, object> dic = QQHelper.get_user_info(config,oauth_access_token, oauth_openid);
            if (dic == null)
            {
                this.Write("{\"ret\":\"1\", \"msg\":\"出错啦，无法获取授权用户信息！\"}");
                return null;
            }
            try
            {
                if (dic["ret"].ToString() != "0")
                {
                    this.Write("{\"ret\":\"" + dic["ret"].ToString() + "\", \"msg\":\"出错信息:" + dic["msg"].ToString() + "！\"}");
                    return null;
                }
                this.Write("{");
                this.Write("\"ret\": \"" + dic["ret"].ToString() + "\", ");
                this.Write("\"msg\": \"" + dic["msg"].ToString() + "\", ");
                this.Write("\"oauth_name\": \"" + oauth_name + "\", ");
                this.Write("\"oauth_access_token\": \"" + oauth_access_token + "\", ");
                this.Write("\"oauth_openid\": \"" + oauth_openid + "\", ");
                this.Write("\"nick\": \"" + dic["nickname"].ToString() + "\", ");
                this.Write("\"avatar\": \"" + dic["figureurl_qq_2"].ToString() + "\", ");
                this.Write("\"sex\": \"" + dic["gender"].ToString() + "\", ");
                this.Write("\"birthday\": \"\"");
                this.Write("}");
            }
            catch
            {
                this.Write("{\"ret\":\"1\", \"msg\":\"出错啦，无法获取授权用户信息！\"}");
            }
            return null;
        }
    }
}
